<?php
/**
 * Created by PhpStorm.
 * User: DELL
 * Date: 2018/7/14
 * Time: 12:27
 */

namespace app\api\controller\v1;
use app\api\controller\Common;
use app\common\lib\Aes;
use app\common\lib\exception\ApiException;

class Index extends Common
{
    /**
     * 获取首页接口
     * 1.头图 4-6
     * 2.推荐位列表 默认40条
     */
    public function index()
    {
        //获取头图位数据 (栏目数据)
        $heads = model('news')->getIndexHeadNormalNews();
        $heads = $this->getDealNews($heads);

        //获取推荐位数据
        $position = model('news')->getPositionNormalNews();
        $position = $this->getDealNews($position);

        $result = [
            'heads'=>$heads,
            'position'=>$position
        ];

        return show(1,'ok',$result,200);
    }

    /**
     * 客户端初始化接口
     * 检测app是否要升级
     * @return ApiException|array
     */
    public function init()
    {
        //TODO:try catch
        $version = model('Version')->getLastNormalVersionByAppType($this->headers['type']);

        if(empty($version))
        {
            return new ApiException('error',404);
        }

        if($version->version > $this->headers['version'])
        {
            //这种写法可以新增一个字段值,是数据库里面没有的
            $version->is_update = $version->is_force == 1 ? 2 : 1;
        }else{
            $version->is_update = 0;    //0不更新   1需要更新  2强制更新
        }

        //当用户打开app时,记录用户的基本信息 用于统计
        $actives = [
            'version'=>$this->headers['version'],
            'type'=>$this->headers['type'],
            'did'=>$this->headers['did'],
            'model'=>$this->headers['model']
        ];

        try{
            model('AppActive')->add($actives);
        }catch(\Exception $e)
        {
            //这个如果有异常,我们不用抛出异常到客户端
            //可以记录到日志里去
           // return show(0,$e->getMessage());
        }

        return show(1,'ok',$version,200);
    }
}